<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.key" placeholder="部门名称/部门主管"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryData">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="100" sortable>
			</el-table-column>
      <el-table-column prop="intro" label="部门介绍" width="100" sortable>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="150" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门主管" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>
      <el-table-column prop="path" label="路径" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: #1d8ce0">启用</span>
          <span v-else style="color: #ff4d51">启用</span>
        </template>
      </el-table-column>

			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="search.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float: right">
      </el-pagination>
		</el-col>
    
		<!--新增/修改界面-->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" ref="saveForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门介绍" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门主管" prop="manager">
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTreeTh"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="saveForm.state" auto-complete="off"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

	export default {
		data() {
			return {
        employees:[],
        deptTreeTh: [],
				search: {
					key: '',
          pageSize:5,
          currentPage:1
				},
        pageInfo:{
          data: [],
          total: 0
        },
				listLoading: false,
				sels: [],//列表选中列

        saveFormVisible:false,
        saveForm:{
          id:null,
          name:"",
          intro:"",
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          path:"",
          state:""
        }
			}
		},
		methods: {
      //获取上级部门树
      getdeptTree(){
        this.$http.get("/department/deptTreeTh")
            .then(res=>{
              res = res.data;
              if(res.success){
                this.deptTreeTh = res.data
              }
            })
            .catch(res=>{})
      },
      //获取管理员列表
      getManager(){
        this.$http.get("/employee")
            .then(res => {
              res = res.data;
              if(res.success){
                this.employees = res.data
              }
            })
            .catch(res => {})
      },
      //点击新增
      handleAdd(){
        this.saveFormVisible = true;
        this.saveForm = {
          id:null,
          name:"",
          intro:"",
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          path:"",
          state:""
        };
        //调用查询管理员
        this.getManager();
        //获取上级部门树
        this.getdeptTree();
      },
      //当每页条数发生变化
      handleSizeChange(val) {
        this.search.pageSize = val;
        this.getDepartments();
      },
      //当前页发生变化
			handleCurrentChange(val) {
				this.search.currentPage = val;
				this.getDepartments();
			},
      //点击查询
      queryData() {
        this.search.currentPage = 1;
        this.getDepartments();
      },
			//获取部门列表
			getDepartments() {
				this.$http.post("/department",this.search)
            .then(res => {
              res = res.data;
              if(res.success){
                this.pageInfo = res.data;
                this.listLoading = false;
              }
            })
            .catch(res => {});
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          this.$http.delete("/department/"+row.id)
              .then(res => {
                res = res.data;
                if(res.success){
                  this.$message({
                    type:"success",
                    message:"删除成功"
                  })
                }else {
                  this.$message.error("删除失败"+res.msg)
                }
                this.listLoading = false;
                this.queryData();
              })
              .catch(res => {});
				}).catch(() => {

				});
			},
			//显示新增/修改界面
			handleSave: function (index,row) {
				this.saveFormVisible = true;
        this.saveForm = row;
        var split = row.path.split("/");
        var data = [];
        for (let i = 1; i < split.length-1; i++) {
          data.push(Number.parseInt(split[i]));
        }
        this.saveForm.parent = data
        if(!row.parent){
          this.saveForm.parent = {
            id:null,
            name:""
          }
        }
        if(!row.manager){
          this.saveForm.manager = {
            id:null,
            username:""
          }
        }
        //调用查询管理员
        this.getManager();
        //获取上级部门树
        this.getdeptTree();
			},
			//新增/修改
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {})
                .then(() => {
                  //NProgress.start();
                  let para = Object.assign({}, this.saveForm);
                  var parent = para.parent;
                  if(parent.length >= 0){
                    if(parent.length == 0){
                      para.parent = {id:null,name:""}
                    }else {
                      para.parent = {id:parent[parent.length-1],name:""}
                    }
                  };
                  this.$http.put("/department",para)
                      .then(res => {
                        this.saveFormVisible = false;
                        this.$message({
                          type:"success",
                          message:"保存成功"
                        })
                        this.queryData();
                      })
                      .catch(res => {});
						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          this.$http.patch("/department",ids)
              .then(res => {
                res = res.data;
                if(res.success){
                  this.$message({
                    type:"success",
                    message:"删除成功"
                  })
                }else {
                  this.$message.error("删除失败"+res.msg)
                }
                this.listLoading = false;
                this.queryData();
              })
              .catch(res => {});
				}).catch(() => {});
			}
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>